package class2;

/**
 * 在有序数组中，>=某个数的最左的位置
 * [1,2,2,2,3,4,5,6,7,8],找到>=2的做最左的位置？
 * 返回index:1
 */
public class Code05_FindNumber {

    public static void main(String[] args) {
        int num = 6;
        int[] arr = new int[]{1, 2, 2, 2, 3, 6, 6, 6, 6, 6, 6, 7, 7, 8, 9, 12};
        // >=num 的最左边
        int index_l = findLeftNumber(arr, num);
        System.out.println("index_l = " + index_l);
        // >=num 的最右边元素
        int index_r = findRightNumber(arr, 6);
        System.out.println("index_r = " + index_r);
    }

    public static int findLeftNumber(int[] arr, int num) {
        if (arr == null && arr.length == 0) return -1;
        int L = 0;
        int R = arr.length - 1;
        int ans = -1;
        while (L <= R) {
            int mid = L + ((R - L) >> 1);
            if (arr[mid] >= num) { // num >= 中间值时
                ans = mid;
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        return ans;
    }

    public static int findRightNumber(int[] arr, int num) {
        int ans = -1, L = 0, R = arr.length - 1;
        while (L <= R) {
            int mid = L + ((R - L) >> 1);
            if (arr[mid] <= num) {
                ans = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return ans;
    }
}

